Function Return Values: How Does Python Make Functions "Output" Results?
This article introduces Python's function return value mechanism, with the core being the use of the `return` statement to pass results, enabling functions' outputs to be used by subsequent code, which differs from `print` that only displays results. 1. **Necessity of `return`**: The `return` statement returns the computed result, e.g., `add(a,b)` returns `a+b`, and the result can be assigned or used in calculations. Without `return`, the function defaults to returning `None`, making it unusable in subsequent operations (e.g., `None*3` will throw an error). 2. **Return Value Types and Diversity**: Return values support multiple types (numbers, strings, lists, etc.), such as returning the string `"Hello, 小明"` or the list `[1,3,5]`. 3. **Multiple Value Return**: Multiple values can be returned by separating them with commas (essentially tuples). When called, these values can be unpacked and assigned, e.g., `name, age = get_user()`, or `_` can be used to ignore unwanted values. 4. **Function Termination Feature**: After executing `return`, the function stops immediately, and subsequent code is not run. **Conclusion**: To ensure a function produces an effective output, `return` must be used; otherwise, it returns `None`, failing to enable result transmission and calculations. (Note: The full text is approximately 2)
Read More